<?php

namespace app\api\service;

use app\common\model\Config;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;

// 华为短信
class HuaWeiSMS
{
//    protected $url = 'https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1';//接口请求地址|格式:APP接入地址 + 固定接口地址  如APP接入地址 = https://smsapi.cn-north-4.myhuaweicloud.com:443;固定接口地址 = /sms/batchSendSms/v1
//    protected $APP_KEY = 'aA7C5cMU7g45erq509Cw6nyP3K9K';//短信app_key
//    protected $APP_SECRET = 'YohhICoCIk1Q4hLplOvzjT4oSBwY';//短信app_secret
//    protected $sender = '8823122727279';//国内短信签名通道号
//    protected $templateId = 'e11405ebec984af88349d576323288c6';//模板ID
//    protected $signature = '复盘之星';//签名名称
//    protected $statusCallback = '';//选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告


    //发送短信
    public function send($phone, array $msg_arr,$type='验证码类')
    {
        $config = Config::where('group','hua_wei_sms')->field('name,value')->select();
        foreach($config as $v){
            if ($v['name'] == 'url'){
                $url = $v['value'];
            }

            if($type == '验证码类'){
                //发送验证码,如登陆验证码
                if ($v['name'] == 'sender_verify_code'){
                    $sender = $v['value'];
                }
                if ($v['name'] == 'template_id_verify_code'){
                    $template_id = $v['value'];
                }
                //$templateParas = "[\"" . $msg_arr[0] . "\"]"; //模板变量
                $templateParas = json_encode([
                    $msg_arr[0],
                ]);
            }

            if ($type == '开通提示类'){
                //例如开通了会员
                if ($v['name'] == 'sender_inform'){
                    $sender = $v['value'];
                }
                if ($v['name'] == 'template_id_inform'){
                    $template_id = $v['value'];
                }
//                $templateParas = "[\"" . $msg_arr[0] . "\",\"" . $msg_arr[1] . "\"]";
                $templateParas = json_encode([
                    $msg_arr[0],
                    $msg_arr[1]
                ]);
            }

            if ($type == '注册类'){
                //admin后台添加用户
                if ($v['name'] == 'sender_register'){
                    $sender = $v['value'];
                }
                if($v['name'] == 'template_id_register'){
                    $template_id = $v['value'];
                }
                $templateParas = json_encode([
                    $msg_arr[0]
                ]);//模板变量
            }


            if ($v['name'] == 'status_callback'){
                $status_callback = $v['value'];
            }
            if ($v['name'] == 'signature'){
                $signature = $v['value'];
            }
            if ($v['name'] == 'app_key'){
                $app_key = $v['value'];
            }
            if ($v['name'] == 'app_secret'){
                $app_secret = $v['value'];
            }
        }

        $client = new Client();
        $res['code'] = 500;
        $res['msg'] = '失败';
        try {
            $response = $client->request('POST', $url, [
                'form_params' => [
                    'from' => $sender,
                    'to' => $phone,
                    'templateId' => $template_id,//短信模板ID，用于唯一标识短信模板,“templateId”需要与“templateParas”参数配合使用。
                    'templateParas' => $templateParas,//短信模板的变量值
                    'statusCallback' => $status_callback,//用户的回调地址，用于接收短信状态报告
                    'signature' => $signature //使用国内短信通用模板时,必须填写签名名称
                ],
                'headers' => [
                    'Authorization' => 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
                    'X-WSSE' => $this->buildWsseHeader($app_key, $app_secret)
                ],
                'verify' => false //为防止因HTTPS证书认证失败造成API调用失败，需要先忽略证书信任问题
            ]);
            //echo Psr7\str($response); //打印响应信息
            //echo $response -> getStatusCode(); //获取发送状态
            //echo $response ->getBody();//获取发送主题内容
            $data = json_decode($response->getBody(), true);

            if ($data['description'] == 'Success'){
                $res['code'] = 200;
                $res['msg'] = '成功';
            }
        } catch (RequestException $e) {
//            echo Psr7\str($e->getRequest()), "\n";
//            dd(1111,$e->getMessage());
//            if ($e->hasResponse()) {
                //dd(2222,$e->getResponse());
//                echo Psr7\str($e->getResponse());
//            }
        }
        return $res;
    }


    private function buildWsseHeader($app_key, $app_secret){
        date_default_timezone_set('Asia/Shanghai');
        $now = date('Y-m-d\TH:i:s\Z'); //Created
        $nonce = uniqid(); //Nonce
        $base64 = base64_encode(hash('sha256', ($nonce . $now . $app_secret))); //PasswordDigest
        return sprintf("UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"",
            $app_key, $base64, $nonce, $now);
    }


}
